//
//  DetailViewController.m
//  Travel_M_Travel
//
//  Created by dlios on 15-3-26.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DetailViewController.h"
#import "NetworkingHandler.h"
#import "Album.h"
#import "Tracks.h"
#import "UIButton+InitButton.h"
#import "UIImageView+WebCache.h"
#import "AMBlurView.h"
#import "DetailCell.h"
#import "SDRefreshStart.h"
#import "PlayController.h"
#import "STKAudioPlayer.h"
#import "SampleQueueId.h"
#import "DownLoadViewController.h"

@interface DetailViewController ()<UITableViewDataSource, UITableViewDelegate, SDRefreshStartDelegate, PushDelegate, STKAudioPlayerDelegate>
@property (nonatomic, retain)NSMutableArray *arr;
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UIImageView *upImg;
@property (nonatomic, retain)UIView *headerView;
@property (nonatomic, retain)UIView *upView;
@property (nonatomic, retain)UILabel *upLabel;
@property (nonatomic, retain)UIImageView *smallImg;
@property (nonatomic, retain)PlayController *playVC;
@property (nonatomic, strong) STKAudioPlayer *player;
@property (nonatomic, retain)NSMutableArray *urlArr;
@property (nonatomic, retain)UIButton *play;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) NSMutableArray *pramaArr;

@end

@implementation DetailViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.page = 1;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    // 隐藏导航栏
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.pramaArr = [NSMutableArray array];
    // 网络请求
    NSString *str3 = [NSString stringWithFormat:@"%@", self.list.idNumber];
    
    NSString *str = [[@"http://mobile.ximalaya.com/mobile/others/ca/album/track/" stringByAppendingString:str3] stringByAppendingString:@"/true/1/30?device=iPhone"];
    
    
    [NetworkingHandler requestWithUrl:str completion:^(NSDictionary *resultDic) {
        
        
        NSDictionary *bigDic = [resultDic objectForKey:@"album"];
        self.album = [[Album alloc] initWithDic:bigDic];
        
        self.arr = [NSMutableArray array];
        self.urlArr = [NSMutableArray array];
        NSArray *tmpArr = [[resultDic objectForKey:@"tracks"] objectForKey:@"list"];
        for (NSDictionary *dic in tmpArr) {
            Tracks *track = [[Tracks alloc] initWithDic:dic];
            [self.urlArr addObject:track.playUrl32];
            [self.arr addObject:track];
            [track release];
        }
        
        [_tableView reloadData];
        NSString *str1 = self.album.coverOrigin;
        str1 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str1];
        [_upImg setImageWithURL:url];
        
        NSString *str4 = self.album.coverSmall;
        str4 = [str4 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url2 = [NSURL URLWithString:str4];
        [_smallImg setImageWithURL:url2];
        
    }];
    
    // tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    // 刷新&加载
    [SDRefreshStart SDRefeshTableView:self.tableView delegate:self];
    
    // tableView的headerView
    self.headerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, self.tableView.frame.size.width, self.view.frame.size.height*21/80)];
    self.tableView.tableHeaderView = _headerView;
    [_headerView release];
    NSLog(@"~~~%f", self.tableView.frame.origin.x);
    
    // headerView的背景图片
    self.upImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, -20, self.view.frame.size.width, self.headerView.frame.size.height + 20)];
    self.upImg.backgroundColor = [UIColor whiteColor];
    self.upImg.userInteractionEnabled = YES;
    [self.headerView addSubview:_upImg];
    [_upImg release];
    
    // 标题背景
    UIView *titleV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    titleV.backgroundColor = [UIColor blackColor];
    
    titleV.alpha = 0.5;
    [self.view addSubview:titleV];
    [titleV release];
    
    // 标题
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(38, 10, titleV.frame.size.width, titleV.frame.size.height)];
    titleL.text = self.list.title;
    titleL.textColor = [UIColor whiteColor];
    NSLog(@"self.list.title: !!!!%@", self.list.title);
    [titleV addSubview:titleL];
    [titleL release];
    
    // 小图片
    self.smallImg = [[UIImageView alloc] initWithFrame:CGRectMake(30, 60, self.view.frame.size.width / 5, self.view.frame.size.height/9)];
    self.smallImg.userInteractionEnabled = YES;
    [self.headerView addSubview:_smallImg];
    [_smallImg release];
    
    // 播放按钮
    self.play = [UIButton buttonWithType:UIButtonTypeSystem];
    _play.frame = CGRectMake(22, 22, self.smallImg.frame.size.width/3, self.smallImg.frame.size.height/3);
    [_play setBackgroundImage:[[UIImage imageNamed:@"playSmall.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [_play addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    [_play backgroundImageForState:UIControlStateNormal];
    [self.smallImg addSubview:_play];
    
    AMBlurView *abv = [[AMBlurView alloc] initWithFrame:CGRectMake(0, 0, self.upImg.frame.size.width, self.upImg.frame.size.height)];
    abv.userInteractionEnabled = NO;
    abv.alpha = 0.85;
    [self.upImg addSubview:abv];
    [abv release];
    
    // 返回按钮
    UIButton *back = [UIButton buttonWithType:UIButtonTypeSystem];
    back.frame = CGRectMake(5, 30, 25, 25);
    [back setBackgroundImage:[[UIImage imageNamed:@"back.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [titleV addSubview:back];
    
}

- (void)playAction:(UIButton *)play
{
    
    self.player = [STKAudioPlayer sharedInstance];
    NSURL *url = [NSURL URLWithString:[self.urlArr objectAtIndex:self.index]];
    if (_player.state == STKAudioPlayerStateReady) {
        
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(observePlayState) userInfo:nil repeats:YES];
        
        [self.play setBackgroundImage:[[UIImage imageNamed:@"pauseSmall.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else if (_player.state == STKAudioPlayerStatePlaying) {
        [self.play setBackgroundImage:[[UIImage imageNamed:@"playSmall.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_player pause];
    } else if (_player.state == STKAudioPlayerStatePaused) {
        [self.play setBackgroundImage:[[UIImage imageNamed:@"pauseSmall.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_player resume];
    }
}

-(void)observePlayState
{
    NSLog(@"%d", _player.state);
    if (_player.state == 16) {
        NSURL *url = [NSURL URLWithString:[self.urlArr objectAtIndex:self.index += 1]];
        STKDataSource *dataSource = [STKAudioPlayer dataSourceFromURL:url];
        
        [self.player setDataSource:dataSource withQueueItemId:[[SampleQueueId alloc] initWithUrl:url andCount:0]];
        [self.play setBackgroundImage:[UIImage imageNamed:@"pauseSmall.png"] forState:UIControlStateNormal];
    }
}

- (void)backAction:(UIButton *)back
{
    [self.navigationController popViewControllerAnimated:NO];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reusen";
    DetailCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[DetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
    }
    Tracks *track = [self.arr objectAtIndex:indexPath.row];
    cell.track = track;
    cell.delegate = self;
    return cell;
}

- (void)pushViewControllerWithPrama:(id)prama
{
    DownLoadViewController *downVC = [DownLoadViewController shareInstance];
    if (![self.pramaArr containsObject:prama]) {
        [self.pramaArr addObject:prama];
    }
    downVC.arr = self.pramaArr;
    [self.navigationController pushViewController:downVC animated:YES];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.playVC = [PlayController shareInstance];
    
    _playVC.track = [self.arr objectAtIndex:indexPath.row];
    _playVC.row = indexPath.row;
    _playVC.arr = self.arr;
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:_playVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}


-(void)headRefesh
{
    
    self.page = 1;
    NSString *page = [NSString stringWithFormat:@"%ld", self.page];
    [self.arr removeAllObjects];
    
    NSString *str5 = [NSString stringWithFormat:@"%@", self.list.idNumber];
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%@/30?device=iPhone", str5, page];
    [NetworkingHandler requestWithUrl:str completion:^(NSDictionary *resultDic) {
        
        NSDictionary *bigDic = [resultDic objectForKey:@"album"];
        self.album = [[Album alloc] initWithDic:bigDic];
        
        NSArray *tmpArr = [[resultDic objectForKey:@"tracks"] objectForKey:@"list"];
        for (NSDictionary *dic in tmpArr) {
            Tracks *track = [[Tracks alloc] initWithDic:dic];
            [self.arr addObject:track];
            [track release];
        }
        
        [_tableView reloadData];
        NSLog(@"~~~~~~~~！！！！！！%@", self.arr);
        NSString *str1 = self.album.coverOrigin;
        str1 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str1];
        [_upImg setImageWithURL:url];
        
        NSString *str4 = self.album.coverSmall;
        str4 = [str4 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url2 = [NSURL URLWithString:str4];
        [_smallImg setImageWithURL:url2];
        
        //        self.upLabel.text = self.album.title;
        //        NSLog(@"label: ~~~~~%@", self.upLabel.text);
    }];
    
    
}

- (void)footRefesh
{
    self.page++;
    NSString *page = [NSString stringWithFormat:@"%ld", self.page];
    
    
    NSString *str5 = [NSString stringWithFormat:@"%@", self.list.idNumber];
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/track/%@/true/%@/30?device=iPhone", str5, page];
    
    
    [NetworkingHandler requestWithUrl:str completion:^(NSDictionary *resultDic) {
        
        NSDictionary *bigDic = [resultDic objectForKey:@"album"];
        self.album = [[Album alloc] initWithDic:bigDic];
        
        
        NSArray *tmpArr = [[resultDic objectForKey:@"tracks"] objectForKey:@"list"];
        for (NSDictionary *dic in tmpArr) {
            Tracks *track = [[Tracks alloc] initWithDic:dic];
            [self.arr addObject:track];
            [track release];
            
        }
        
        [_tableView reloadData];
        NSLog(@"~~~~~~~~！！！！！！%@", self.arr);
        NSString *str1 = self.album.coverOrigin;
        str1 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str1];
        [_upImg setImageWithURL:url];
        
        NSString *str4 = self.album.coverSmall;
        str4 = [str4 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url2 = [NSURL URLWithString:str4];
        [_smallImg setImageWithURL:url2];
        
        //        self.upLabel.text = self.album.title;
        //        NSLog(@"label: ~~~~~%@", self.upLabel.text);
    }];
    
    
}

-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{
    NSLog(@"播放状态改变");
}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    NSLog(@"结束播放");
    NSLog(@"结束原因: %d, progress: %f, duration: %f", stopReason, progress, duration);
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{
    NSLog(@"错误原因: %d", errorCode);
}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{
    NSLog(@"信息: %@", line);
}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{
    NSLog(@"未知");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
